<template>
  <el-row>
    <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
      <div class="item">
        <div class="tit">服务器硬盘信息</div>
        <div v-if="props.Type != 'hyperV'" class="con">
          <el-progress type="circle" :percentage="oneC" />
        </div>
        <div v-else class="max-h-126px h-126px m-t-20px">
          <el-scrollbar>
            <div v-for="(i, index) in Vm_list_info" :key="index" class="m-b-10px">
              <div class="flex justify-between text-11px text-#449cc7">
                <div>{{ i.device }}</div>
                <div>
                  {{ diskSize(i.used_gb, i.total_gb) }}
                </div>
              </div>
              <el-progress :percentage="percent(i.used_gb, i.total_gb)" color="#409eff" />
            </div>
          </el-scrollbar>
        </div>
        <div class="mes">已使用大小：{{ used }}GB</div>
        <div class="mes2">总大小：{{ all }}GB</div>
      </div>
    </el-col>
    <el-col :xs="24" :sm="6" :md="6" :lg="6" :xl="6">
      <div class="item">
        <div class="tit">服务器实际划分硬盘信息</div>
        <div class="con">
          <el-progress type="circle" :percentage="twoC" />
        </div>
        <div class="mes">实际划分大小：{{ realdisk }}GB</div>
      </div>
    </el-col>
    <el-col :xs="24" :sm="11" :md="11" :lg="11" :xl="11">
      <div class="item">
        <div id="mychart" />
      </div>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { getDiskInfo, getRealDisk, getTraffic } from "@/api/server";
import { ref, onMounted, onBeforeUnmount, watch, defineProps } from "vue";
import { useRoute } from "vue-router";
import * as echarts from "echarts";
import { diskSize, percent } from "@/utils/hide";

const props = defineProps(["Type"]);
const route = useRoute();
const server_id = ref(route.query.server_id);
const realdisk = ref(0);
const used = ref(0);
const all = ref(0);
const oneC = ref(0);
const twoC = ref(0);
const timelist = ref<string[]>([]);
const topline = ref<number[]>([]);
const downline = ref<number[]>([]);

const timer = ref<NodeJS.Timeout | null>(null);
let myChart = ref<echarts.ECharts | null>(null);

onMounted(async () => {
  console.log("类型", props.Type);
  if (props.Type == "hyperV") {
    await getVmInfo();
  } else {
    await initializeData();
  }
  setupChart();

  // 每10秒更新一次数据和图表
  timer.value = setInterval(() => {
    getInfo();
    updateChart();
  }, 5000);

  window.addEventListener("resize", () => {
    if (myChart.value) {
      myChart.value.resize();
    }
  });
});

onBeforeUnmount(() => {
  // 在组件卸载前清除定时器
  if (timer.value) {
    clearInterval(timer.value);
  }
  window.removeEventListener("resize", () => {
    if (myChart.value) {
      myChart.value.resize();
    }
  });
});
// 获取虚拟机信息
const Vm_list_info = ref([]);
const getVmInfo = async () => {
  await getDiskInfo(server_id.value).then(async res => {
    Vm_list_info.value = res.data.data.data;
    let VmNum = res.data.data.data.reduce(
      (sum, disk) => sum + disk.total_gb,
      0
    );
    let VmNumGB = res.data.data.data.reduce(
      (sum, disk) => sum + disk.used_gb,
      0
    );
    await getRealDisk(server_id.value).then(res => {
      realdisk.value = res.data.data.desk;
      twoC.value = parseFloat((realdisk.value / VmNum) * 100).toFixed(2);
    });
    all.value = VmNum.toFixed(2);
    used.value = VmNumGB.toFixed(2);
    console.log(VmNum, VmNumGB);
  });
};
// 获取容器信息
const initializeData = async () => {
  await getDiskInfo(server_id.value).then(async res => {
    used.value = (res.data.data.data.used / 1024 / 1024 / 1024).toFixed(2);
    all.value = (res.data.data.data.total / 1024 / 1024 / 1024).toFixed(2);
    oneC.value = parseFloat((used.value / all.value) * 100).toFixed(2);
    await getRealDisk(server_id.value).then(res => {
      realdisk.value = res.data.data.desk;
      twoC.value = parseFloat((realdisk.value / all.value) * 100).toFixed(2);
    });
  });
};

const setupChart = () => {
  const chartDom = document.getElementById("mychart");
  if (chartDom) {
    myChart.value = echarts.init(chartDom);
    getTraffic(server_id.value).then(res => {
      timelist.value.push(new Date().toLocaleString());
      if (props.Type == "hyperV") {
        topline.value.push(parseFloat(res.data.data.data.tx / 1024).toFixed(2));
        downline.value.push(
          parseFloat(res.data.data.data.rx / 1024).toFixed(2)
        );
      } else {
        topline.value.push(res.data.data.data.sent);
        downline.value.push(res.data.data.data.recv);
      }
      const option = {
        title: {
          text: "服务器流量信息"
        },
        tooltip: {
          trigger: "item"
        },
        legend: {
          data: ["上行流量(KB)", "下行流量(KB)"]
        },
        grid: {
          left: "3%",
          right: "4%",
          bottom: "3%",
          containLabel: true
        },
        toolbox: {
          feature: {
            saveAsImage: {}
          }
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: timelist.value
        },
        yAxis: {
          type: "value",
          axisLabel: {
            formatter: "{value} KB/s"
          }
        },
        series: [
          {
            name: "上行流量(KB)",
            type: "line",
            data: topline.value
          },
          {
            name: "下行流量(KB)",
            type: "line",
            data: downline.value
          }
        ]
      };
      myChart.value?.setOption(option);
    });
  }
};

const getInfo = () => {
  getTraffic(server_id.value).then(res => {
    if (res.data.data) {
      if (props.Type == "hyperV") {
        if (timelist.value.length < 10) {
          timelist.value.push(new Date().toLocaleString());
        } else {
          timelist.value.shift();
          timelist.value.push(new Date().toLocaleString());
        }
        if (topline.value.length < 10) {
          topline.value.push(
            parseFloat(res.data.data.data.tx / 1024).toFixed(2)
          );
        } else {
          topline.value.shift();
          topline.value.push(
            parseFloat(res.data.data.data.tx / 1024).toFixed(2)
          );
        }
        if (downline.value.length < 10) {
          downline.value.push(
            parseFloat(res.data.data.data.rx / 1024).toFixed(2)
          );
        } else {
          downline.value.shift();
          downline.value.push(
            parseFloat(res.data.data.data.rx / 1024).toFixed(2)
          );
        }
      } else {
        if (timelist.value.length < 10) {
          timelist.value.push(new Date().toLocaleString());
        } else {
          timelist.value.shift();
          timelist.value.push(new Date().toLocaleString());
        }
        if (topline.value.length < 10) {
          topline.value.push(res.data.data.data.sent);
        } else {
          topline.value.shift();
          topline.value.push(res.data.data.data.sent);
        }
        if (downline.value.length < 10) {
          downline.value.push(res.data.data.data.recv);
        } else {
          downline.value.shift();
          downline.value.push(res.data.data.data.recv);
        }
      }
    } else {
      // 请求为空时清除定时器
      clearInterval(timer.value);
      timer.value = null;
    }
  });
};

const updateChart = () => {
  if (timelist.value && myChart.value) {
    const option = {
      xAxis: {
        data: timelist.value
      },
      series: [
        {
          data: topline.value
        },
        {
          data: downline.value
        }
      ]
    };
    myChart.value.setOption(option);
  }
};
</script>
<style lang="scss" scoped>
.el-row {
  width: 100%;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
}

.el-col {
  border-radius: 4px;
  height: 260px;
  margin-bottom: 20px;

  .item {
    height: 100%;
    background-color: white;
    border-radius: 3px;
    box-sizing: border-box;
    padding: 20px;

    .tit {
      font-size: 16px;
      font-weight: bold;
    }

    .con {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }

    .mes {
      font-size: 12px;
      margin-top: 15px;
    }

    .mes2 {
      font-size: 12px;
      margin-top: 5px;
    }

    #mychart {
      height: 95%;
      width: 100%;
    }
  }
}

.ovf {
  overflow-y: auto;
}

:deep(.el-progress__text) {
  min-width: 28px;
  font-size: 11px;
}
</style>
